#!/usr/bin/env python
########################################################################
#  Quote - On-line historical quotes
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
########################################################################
#  Adapted code from pyq.py - originally authored by Rimon Barr
"""Retrieve historical quotes from finance.yahoo.com"""
import urllib
import re
import quote

def get(ticker, d1, d2):
    d1 = quote.beforeFirst(d1) # make sure we have a previous "base" quote
    quote.info("yahoo.get(%s, %s, %s)", ticker, d1, d2)
    def parseDate(d):
        return (d[:-4], d[-4:-2], d[-2:])
    d1=parseDate(d1)
    d2=parseDate(d2)
    url='http://ichart.finance.yahoo.com/table.csv'
    query = (
        ('a', '%02d' % (int(d1[1])-1)),
        ('b', d1[2]),
        ('c', d1[0]),
        ('d', '%02d' % (int(d2[1])-1)),
        ('e', d2[2]),
        ('f', d2[0]),
        ('s', ticker),
        ('y', '0'),
        ('g', 'd'),
        ('ignore', '.csv'),
    )
    lines=urllib.urlopen(url+'?'+urllib.urlencode(query)).read().splitlines()
    if re.match('(no prices|.*html.*)', lines[0], re.I): 
        return {}
    lines=lines[1:len(lines)]
    result = {}
    for l in lines:
        if l[-1] == '\r':
            l = l[:-1]
        date, open, high, low, close, volume, adjusted = l.split(',')
        date="".join(date.split("-"))
        result[date] = {'open':open, 'high':high, 'low':low, 
                        'close':close, 'volume':volume, 
                        'adjusted':adjusted}
    quote.adjusted2coef(result)
    return result
